package com.cykj.cotroller;

import com.cykj.service.WordCreateService1;
import com.cykj.vo.orderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@RestController
@RequestMapping("/report")
public class WordCreateController1 {
    @Autowired
    private WordCreateService1 wordCreateService;


    @RequestMapping("/generate")
    public ResponseEntity<byte[]> generateReport(@RequestBody orderVo vo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String filePath = "D:\\体检报告_" + sdf.format(new Date()) + ".docx";

        wordCreateService.exportWordReport(filePath, vo.getUserId(), vo.getOrderId());

        try (FileInputStream fis = new FileInputStream(filePath)) {
            // 计算文件长度
            int fileLength = fis.available();
            byte[] content = new byte[fileLength];
            int bytesRead = 0;
            int bytesToRead = fileLength;
            while (bytesToRead > 0) {
                int result = fis.read(content, bytesRead, bytesToRead);
                if (result == -1) {
                    break;
                }
                bytesRead += result;
                bytesToRead -= result;
            }
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 设置文件名，确保浏览器能正确识别
            headers.setContentDispositionFormData("attachment", "体检报告_" + sdf.format(new Date()) + ".docx");
            return new ResponseEntity<>(content, headers, HttpStatus.OK);
        } catch (FileNotFoundException e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
